const minio = require("../minio");
const router = require("../router");
const multer = require("multer");
const path = require("path");
const fs = require("fs");

router.post("/listObjects", function (req, res) {
  const params = req.body;

  const { bucketName, prefix, pageSize, pageNum } = params;

  const stream = minio().listObjects(bucketName, prefix || "", false);

  let flag = false,
    data = [];

  stream.on("data", function (obj) {
    data.push(obj);
    flag = true;
  });

  stream.on("error", function (err) {
    console.log(err);

    data = err;
    flag = false;
  });

  stream.on("end", function (err) {
    if (flag) {
      // 分页处理
      res.json({
        code: "0",
        data:
          pageNum == -1
            ? {
                total: data.length,
                lists: data,
              }
            : {
                total: data.length,
                lists: pagination(data, pageSize || 10, pageNum || 1),
              },
        msg: "成功",
        success: true,
      });
    } else {
      res.json({
        code: "-1",
        data: err,
        msg: "失败",
        success: false,
      });
    }
  });
});

router.post("/getObject", function (req, res) {
  const params = req.body;

  const { bucketName, objectName } = params;

  minio().getObject(bucketName, objectName, function (err, dataStream) {
    if (err) {
      return console.log(err);
    }
    let size = 0;

    dataStream.on("data", function (chunk) {
      size += chunk.length;
    });
    dataStream.on("end", function () {
      res.json({
        code: "0",
        data: size,
        msg: "成功",
        success: true,
      });
    });
    dataStream.on("error", function (err) {
      res.json({
        code: "-1",
        data: err,
        msg: "失败",
        success: false,
      });
    });
  });
});

router.post("/statObject", function (req, res) {
  const params = req.body;

  const { bucketName, objectName } = params;

  minio().statObject(bucketName, objectName, function (err, stat) {
    if (err) {
      return console.log(err);
    }

    res.json({
      code: "0",
      data: stat,
      msg: "成功",
      success: true,
    });
  });
});

router.post("/presignedGetObject", function (req, res) {
  const params = req.body;

  const { bucketName, objectName, expiry } = params;

  minio().presignedGetObject(
    bucketName,
    objectName,
    expiry || 7 * 24 * 60 * 60,
    function (err, presignedUrl) {
      if (err) {
        return console.log(err);
      }

      res.json({
        code: "0",
        data: presignedUrl,
        msg: "成功",
        success: true,
      });
    }
  );
});

router.post("/putFolder", async function (req, res) {
  console.log("/putFolder", req.body);

  const bucketName = req.body.bucket,
    folder = req.body.folder;

  minio().putObject(bucketName, folder + "/", "", "", "", function (err, etag) {
    if (err) {
      return res.json({
        code: "-1",
        data: err,
        msg: "失败",
        success: false,
      });
    } else {
      return res.json({
        code: "0",
        data: etag,
        msg: "成功",
        success: true,
      });
    }
  });
});

router.post(
  "/putObject",
  multer({
    dest: path.resolve(__dirname, "../../../../db/__temp__"),
  }).single("file"),
  async function (req, res) {
    console.log("/putObject", req.file, req.headers);

    console.log("verifyResponse", verifyResponse);
    const useExt = (ext) => {
      switch (ext) {
        case "svg":
          return "svg+xml";
        default:
          return ext;
      }
    };

    const bucketName = req.headers.bucket,
      folder = req.headers.folder,
      originName = req.file["originalname"],
      file = req.file["path"],
      ext = useExt(path.extname(req.file["originalname"]).slice(1)),
      fileName = req.file["filename"];

    const fullName = folder ? `${folder}/${originName}` : `${originName}`;
    fs.stat(file, function (err, stats) {
      if (err) {
        return console.log(err);
      }
      minio().putObject(
        bucketName,
        fullName,
        fs.createReadStream(file),
        stats.size,
        {
          "Content-Type": `image/${ext}`,
        },
        function (err, etag) {
          fs.unlink(
            path.resolve(__dirname, `../../../../db/__temp__/${fileName}`),
            function (err) {
              if (err) {
                console.error(`删除文件 ${fileName} 失败，失败原因：${err}`);
              }
              console.log(`删除文件 ${fileName} 成功`);
            }
          );
          if (err) {
            return res.json({
              code: "-1",
              data: err,
              msg: "失败",
              success: false,
            });
          } else {
            return res.json({
              code: "0",
              data: etag,
              msg: "成功",
              success: true,
            });
          }
        }
      );
    });
  }
);

router.post("/removeObject", async function (req, res) {
  console.log("/removeObject", req.body, req.headers);

  const {
    bucketName,
    objectName
  } = req.body;
  minio().removeObject(bucketName, objectName, function (err) {
    if (err) {
      return res.json({
        code: "-1",
        data: err,
        msg: '失败',
        success: false
      })
    }
    return res.json({
      code: "0",
      data: {},
      msg: '成功',
      success: true
    })
  })
});

module.exports = router;
